﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

using CNCSoft.EData;
using CNCSoft.EWinform.AGrid;

namespace CNCSoft.EWinform.ERPApps {

	/// <summary>
	/// Summary description for DataListManager.
	/// </summary>
	public class DataListManager : System.Windows.Forms.Form, ICreateNewAbility {

		private System.Windows.Forms.StatusBarPanel sbpMessage;
		private System.Windows.Forms.StatusBarPanel sbpUser;
		private System.Windows.Forms.StatusBarPanel sbpServer;
		private System.Windows.Forms.Panel pnlMain;
		private System.Windows.Forms.Splitter splitter1;
		private System.Windows.Forms.TreeView tvDataList;
		private System.Windows.Forms.Panel pnlDataList;
		private System.Windows.Forms.TabControl tabControl1;
		private System.Windows.Forms.TabPage tpDataList;
		private System.Windows.Forms.TabPage tpDataListMan;
		private System.Windows.Forms.TabPage tpHelp;
		private System.Windows.Forms.ImageList imageList1;
		private System.Windows.Forms.TabPage tpUserPermit;
		private System.Windows.Forms.RichTextBox rtbHelp;
		private System.Windows.Forms.Panel panel1;
		private System.Windows.Forms.Splitter splitter2;
		private System.Windows.Forms.Panel panel3;
		private System.Windows.Forms.Panel panel4;
		private System.Windows.Forms.Panel panel5;
		private System.Windows.Forms.Panel panel2;
		private System.Windows.Forms.Panel pnlGridDanhMuc;
		private System.Windows.Forms.Panel pnlTestQuery;
		private System.Windows.Forms.Splitter splitter3;
		private System.Windows.Forms.DataGrid dgridTestQuey;
		private System.Windows.Forms.Button cmdTestQuery;
		private System.Windows.Forms.Button cmdUpdate;
		private System.Windows.Forms.DataGrid dgridDataListEdit;
		private System.Windows.Forms.DataGrid dgridDataListCreate;
		private System.Windows.Forms.ToolTip toolTip1;
		private System.Windows.Forms.TreeView tvUsernGroup;
		private System.Windows.Forms.StatusBar stbMain;
		private System.Windows.Forms.Button cmdUpdateUGPermit;
		private System.Windows.Forms.CheckedListBox chklstUGPermit;
		private System.Windows.Forms.Panel pnlDataList_CMD;
		private System.Windows.Forms.Button cmdUpdateDL;
		private System.Windows.Forms.Panel pnlDataList_Right;
		private System.Windows.Forms.Panel pnlDataList_Grid;
		private System.Windows.Forms.Button cmdCancelDL;
		private System.Windows.Forms.Panel pnlDataListMan_Dgrid;
		private System.Windows.Forms.Panel pnlDataList_Man_CMD;
		private System.Windows.Forms.Panel pnlDataList_Man_UG;
		private System.Windows.Forms.ImageList imageList2;
		private System.Windows.Forms.TabPage tpErrorLog;
		private System.Windows.Forms.TextBox txtErrorLog;
		private System.Windows.Forms.ErrorProvider ep;
		private System.Windows.Forms.Label lblError;
		private System.Windows.Forms.ContextMenu cmTVDataList;
		private System.Windows.Forms.MenuItem mniRefresh;
		private System.Windows.Forms.CheckBox chkCheckAll;
		private System.Windows.Forms.Button cmdPhanQuyen;
		private System.ComponentModel.IContainer components;

		public DataListManager(string cnnString, UserInfo loginUser, string returnIdColumnName) {
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			_cnnInfo = new CNCSoft.EData.SqlServer.SqlConnectionInfo(cnnString);
			_loginUser = loginUser;
			Users u = new Users(cnnString);
			errorIcon = (Icon)sbpMessage.Icon.Clone();
			sbpMessage.Icon = null;
			this.returnColumnName = returnIdColumnName;

			try {
				isSuperVisor = u.isSuperVisor(_loginUser.UserID);
			}
			catch (Exception ex) {
				isReload = true;
				sendStatusMessage("Không thể kiểm tra các đặc quyền của [" +_loginUser.UserID +"].", true);
				logError(ex);
			}
		}

		public DataListManager(string cnnString, UserInfo loginUser):this(cnnString, loginUser, null) {
		}

		public DataListManager(string cnnString, string userId, string returnIdColumnName):
			this(cnnString, new UserInfo(userId, null, null), returnIdColumnName) {
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing ) {
			if( disposing ) {
				if(components != null) {
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DataListManager));
            this.stbMain = new System.Windows.Forms.StatusBar();
            this.sbpMessage = new System.Windows.Forms.StatusBarPanel();
            this.sbpUser = new System.Windows.Forms.StatusBarPanel();
            this.sbpServer = new System.Windows.Forms.StatusBarPanel();
            this.pnlMain = new System.Windows.Forms.Panel();
            this.pnlDataList_Right = new System.Windows.Forms.Panel();
            this.pnlDataList_Grid = new System.Windows.Forms.Panel();
            this.dgridDataListEdit = new System.Windows.Forms.DataGrid();
            this.pnlDataList_CMD = new System.Windows.Forms.Panel();
            this.cmdUpdateDL = new System.Windows.Forms.Button();
            this.cmdCancelDL = new System.Windows.Forms.Button();
            this.splitter1 = new System.Windows.Forms.Splitter();
            this.pnlDataList = new System.Windows.Forms.Panel();
            this.tvDataList = new System.Windows.Forms.TreeView();
            this.cmTVDataList = new System.Windows.Forms.ContextMenu();
            this.mniRefresh = new System.Windows.Forms.MenuItem();
            this.imageList2 = new System.Windows.Forms.ImageList(this.components);
            this.tabControl1 = new System.Windows.Forms.TabControl();
            this.tpDataList = new System.Windows.Forms.TabPage();
            this.tpUserPermit = new System.Windows.Forms.TabPage();
            this.panel1 = new System.Windows.Forms.Panel();
            this.panel3 = new System.Windows.Forms.Panel();
            this.panel5 = new System.Windows.Forms.Panel();
            this.chklstUGPermit = new System.Windows.Forms.CheckedListBox();
            this.panel4 = new System.Windows.Forms.Panel();
            this.chkCheckAll = new System.Windows.Forms.CheckBox();
            this.cmdUpdateUGPermit = new System.Windows.Forms.Button();
            this.splitter2 = new System.Windows.Forms.Splitter();
            this.pnlDataList_Man_UG = new System.Windows.Forms.Panel();
            this.tvUsernGroup = new System.Windows.Forms.TreeView();
            this.tpDataListMan = new System.Windows.Forms.TabPage();
            this.panel2 = new System.Windows.Forms.Panel();
            this.splitter3 = new System.Windows.Forms.Splitter();
            this.pnlGridDanhMuc = new System.Windows.Forms.Panel();
            this.pnlDataListMan_Dgrid = new System.Windows.Forms.Panel();
            this.dgridDataListCreate = new System.Windows.Forms.DataGrid();
            this.pnlDataList_Man_CMD = new System.Windows.Forms.Panel();
            this.cmdUpdate = new System.Windows.Forms.Button();
            this.cmdPhanQuyen = new System.Windows.Forms.Button();
            this.cmdTestQuery = new System.Windows.Forms.Button();
            this.pnlTestQuery = new System.Windows.Forms.Panel();
            this.dgridTestQuey = new System.Windows.Forms.DataGrid();
            this.tpHelp = new System.Windows.Forms.TabPage();
            this.rtbHelp = new System.Windows.Forms.RichTextBox();
            this.tpErrorLog = new System.Windows.Forms.TabPage();
            this.txtErrorLog = new System.Windows.Forms.TextBox();
            this.imageList1 = new System.Windows.Forms.ImageList(this.components);
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.ep = new System.Windows.Forms.ErrorProvider(this.components);
            this.lblError = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.sbpMessage)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbpUser)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbpServer)).BeginInit();
            this.pnlMain.SuspendLayout();
            this.pnlDataList_Right.SuspendLayout();
            this.pnlDataList_Grid.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dgridDataListEdit)).BeginInit();
            this.pnlDataList_CMD.SuspendLayout();
            this.pnlDataList.SuspendLayout();
            this.tabControl1.SuspendLayout();
            this.tpDataList.SuspendLayout();
            this.tpUserPermit.SuspendLayout();
            this.panel1.SuspendLayout();
            this.panel3.SuspendLayout();
            this.panel5.SuspendLayout();
            this.panel4.SuspendLayout();
            this.pnlDataList_Man_UG.SuspendLayout();
            this.tpDataListMan.SuspendLayout();
            this.panel2.SuspendLayout();
            this.pnlGridDanhMuc.SuspendLayout();
            this.pnlDataListMan_Dgrid.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dgridDataListCreate)).BeginInit();
            this.pnlDataList_Man_CMD.SuspendLayout();
            this.pnlTestQuery.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dgridTestQuey)).BeginInit();
            this.tpHelp.SuspendLayout();
            this.tpErrorLog.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.ep)).BeginInit();
            this.SuspendLayout();
            // 
            // stbMain
            // 
            this.stbMain.Location = new System.Drawing.Point(0, 408);
            this.stbMain.Name = "stbMain";
            this.stbMain.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
            this.sbpMessage,
            this.sbpUser,
            this.sbpServer});
            this.stbMain.ShowPanels = true;
            this.stbMain.Size = new System.Drawing.Size(736, 22);
            this.stbMain.TabIndex = 0;
            this.stbMain.Text = "statusBar1";
            // 
            // sbpMessage
            // 
            this.sbpMessage.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
            this.sbpMessage.Icon = ((System.Drawing.Icon)(resources.GetObject("sbpMessage.Icon")));
            this.sbpMessage.Name = "sbpMessage";
            this.sbpMessage.Width = 519;
            // 
            // sbpUser
            // 
            this.sbpUser.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
            this.sbpUser.Name = "sbpUser";
            this.sbpUser.ToolTipText = "Login user !.";
            // 
            // sbpServer
            // 
            this.sbpServer.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
            this.sbpServer.Name = "sbpServer";
            this.sbpServer.ToolTipText = "Working server !";
            // 
            // pnlMain
            // 
            this.pnlMain.Controls.Add(this.pnlDataList_Right);
            this.pnlMain.Controls.Add(this.splitter1);
            this.pnlMain.Controls.Add(this.pnlDataList);
            this.pnlMain.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pnlMain.Location = new System.Drawing.Point(0, 0);
            this.pnlMain.Name = "pnlMain";
            this.pnlMain.Size = new System.Drawing.Size(728, 370);
            this.pnlMain.TabIndex = 1;
            // 
            // pnlDataList_Right
            // 
            this.pnlDataList_Right.Controls.Add(this.pnlDataList_Grid);
            this.pnlDataList_Right.Controls.Add(this.pnlDataList_CMD);
            this.pnlDataList_Right.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pnlDataList_Right.Location = new System.Drawing.Point(187, 0);
            this.pnlDataList_Right.Name = "pnlDataList_Right";
            this.pnlDataList_Right.Size = new System.Drawing.Size(541, 370);
            this.pnlDataList_Right.TabIndex = 0;
            // 
            // pnlDataList_Grid
            // 
            this.pnlDataList_Grid.Controls.Add(this.dgridDataListEdit);
            this.pnlDataList_Grid.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pnlDataList_Grid.Location = new System.Drawing.Point(0, 0);
            this.pnlDataList_Grid.Name = "pnlDataList_Grid";
            this.pnlDataList_Grid.Size = new System.Drawing.Size(541, 322);
            this.pnlDataList_Grid.TabIndex = 2;
            // 
            // dgridDataListEdit
            // 
            this.dgridDataListEdit.CaptionText = "Bạn vui lòng chọn danh mục để chỉnh sửa";
            this.dgridDataListEdit.DataMember = "";
            this.dgridDataListEdit.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dgridDataListEdit.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dgridDataListEdit.Location = new System.Drawing.Point(0, 0);
            this.dgridDataListEdit.Name = "dgridDataListEdit";
            this.dgridDataListEdit.Size = new System.Drawing.Size(541, 322);
            this.dgridDataListEdit.TabIndex = 0;
            // 
            // pnlDataList_CMD
            // 
            this.pnlDataList_CMD.Controls.Add(this.cmdUpdateDL);
            this.pnlDataList_CMD.Controls.Add(this.cmdCancelDL);
            this.pnlDataList_CMD.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.pnlDataList_CMD.Location = new System.Drawing.Point(0, 322);
            this.pnlDataList_CMD.Name = "pnlDataList_CMD";
            this.pnlDataList_CMD.Size = new System.Drawing.Size(541, 48);
            this.pnlDataList_CMD.TabIndex = 1;
            // 
            // cmdUpdateDL
            // 
            this.cmdUpdateDL.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.cmdUpdateDL.Cursor = System.Windows.Forms.Cursors.Hand;
            this.cmdUpdateDL.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.cmdUpdateDL.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cmdUpdateDL.ForeColor = System.Drawing.Color.Crimson;
            this.cmdUpdateDL.Image = ((System.Drawing.Image)(resources.GetObject("cmdUpdateDL.Image")));
            this.cmdUpdateDL.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.cmdUpdateDL.Location = new System.Drawing.Point(196, 6);
            this.cmdUpdateDL.Name = "cmdUpdateDL";
            this.cmdUpdateDL.Size = new System.Drawing.Size(174, 36);
            this.cmdUpdateDL.TabIndex = 0;
            this.cmdUpdateDL.Text = "Cập nhật các thay đổi";
            this.cmdUpdateDL.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.cmdUpdateDL.Click += new System.EventHandler(this.cmdUpdateDL_Click);
            // 
            // cmdCancelDL
            // 
            this.cmdCancelDL.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.cmdCancelDL.Cursor = System.Windows.Forms.Cursors.Hand;
            this.cmdCancelDL.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.cmdCancelDL.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cmdCancelDL.ForeColor = System.Drawing.Color.Crimson;
            this.cmdCancelDL.Image = ((System.Drawing.Image)(resources.GetObject("cmdCancelDL.Image")));
            this.cmdCancelDL.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.cmdCancelDL.Location = new System.Drawing.Point(374, 6);
            this.cmdCancelDL.Name = "cmdCancelDL";
            this.cmdCancelDL.Size = new System.Drawing.Size(162, 36);
            this.cmdCancelDL.TabIndex = 1;
            this.cmdCancelDL.Text = "Bỏ qua các thay đổi";
            this.cmdCancelDL.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.cmdCancelDL.Click += new System.EventHandler(this.cmdCancelDL_Click);
            // 
            // splitter1
            // 
            this.splitter1.Location = new System.Drawing.Point(184, 0);
            this.splitter1.Name = "splitter1";
            this.splitter1.Size = new System.Drawing.Size(3, 370);
            this.splitter1.TabIndex = 1;
            this.splitter1.TabStop = false;
            // 
            // pnlDataList
            // 
            this.pnlDataList.Controls.Add(this.tvDataList);
            this.pnlDataList.Dock = System.Windows.Forms.DockStyle.Left;
            this.pnlDataList.Location = new System.Drawing.Point(0, 0);
            this.pnlDataList.Name = "pnlDataList";
            this.pnlDataList.Size = new System.Drawing.Size(184, 370);
            this.pnlDataList.TabIndex = 0;
            // 
            // tvDataList
            // 
            this.tvDataList.ContextMenu = this.cmTVDataList;
            this.tvDataList.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tvDataList.ImageIndex = 1;
            this.tvDataList.ImageList = this.imageList2;
            this.tvDataList.Location = new System.Drawing.Point(0, 0);
            this.tvDataList.Name = "tvDataList";
            this.tvDataList.SelectedImageIndex = 2;
            this.tvDataList.Size = new System.Drawing.Size(184, 370);
            this.tvDataList.TabIndex = 0;
            this.toolTip1.SetToolTip(this.tvDataList, "Danh sách các danh mục mà bạn được quyển chỉnh sửa !.");
            this.tvDataList.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvDataList_AfterSelect);
            // 
            // cmTVDataList
            // 
            this.cmTVDataList.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.mniRefresh});
            // 
            // mniRefresh
            // 
            this.mniRefresh.Index = 0;
            this.mniRefresh.Shortcut = System.Windows.Forms.Shortcut.F5;
            this.mniRefresh.Text = "Refresh";
            this.mniRefresh.Click += new System.EventHandler(this.mniRefresh_Click);
            // 
            // imageList2
            // 
            this.imageList2.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList2.ImageStream")));
            this.imageList2.TransparentColor = System.Drawing.Color.Transparent;
            this.imageList2.Images.SetKeyName(0, "");
            this.imageList2.Images.SetKeyName(1, "");
            this.imageList2.Images.SetKeyName(2, "");
            this.imageList2.Images.SetKeyName(3, "");
            this.imageList2.Images.SetKeyName(4, "");
            this.imageList2.Images.SetKeyName(5, "");
            // 
            // tabControl1
            // 
            this.tabControl1.Appearance = System.Windows.Forms.TabAppearance.FlatButtons;
            this.tabControl1.Controls.Add(this.tpDataList);
            this.tabControl1.Controls.Add(this.tpUserPermit);
            this.tabControl1.Controls.Add(this.tpDataListMan);
            this.tabControl1.Controls.Add(this.tpHelp);
            this.tabControl1.Controls.Add(this.tpErrorLog);
            this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControl1.ImageList = this.imageList1;
            this.tabControl1.Location = new System.Drawing.Point(0, 0);
            this.tabControl1.Name = "tabControl1";
            this.tabControl1.SelectedIndex = 0;
            this.tabControl1.Size = new System.Drawing.Size(736, 408);
            this.tabControl1.TabIndex = 0;
            this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged);
            // 
            // tpDataList
            // 
            this.tpDataList.BackColor = System.Drawing.Color.WhiteSmoke;
            this.tpDataList.Controls.Add(this.pnlMain);
            this.tpDataList.ImageIndex = 0;
            this.tpDataList.Location = new System.Drawing.Point(4, 34);
            this.tpDataList.Name = "tpDataList";
            this.tpDataList.Size = new System.Drawing.Size(728, 370);
            this.tpDataList.TabIndex = 0;
            this.tpDataList.Text = "Danh mục";
            // 
            // tpUserPermit
            // 
            this.tpUserPermit.BackColor = System.Drawing.Color.WhiteSmoke;
            this.tpUserPermit.Controls.Add(this.panel1);
            this.tpUserPermit.ImageIndex = 1;
            this.tpUserPermit.Location = new System.Drawing.Point(4, 34);
            this.tpUserPermit.Name = "tpUserPermit";
            this.tpUserPermit.Size = new System.Drawing.Size(728, 370);
            this.tpUserPermit.TabIndex = 3;
            this.tpUserPermit.Text = "Phân quyền sử dụng";
            // 
            // panel1
            // 
            this.panel1.Controls.Add(this.panel3);
            this.panel1.Controls.Add(this.splitter2);
            this.panel1.Controls.Add(this.pnlDataList_Man_UG);
            this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel1.Location = new System.Drawing.Point(0, 0);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(728, 370);
            this.panel1.TabIndex = 0;
            // 
            // panel3
            // 
            this.panel3.Controls.Add(this.panel5);
            this.panel3.Controls.Add(this.panel4);
            this.panel3.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel3.Location = new System.Drawing.Point(171, 0);
            this.panel3.Name = "panel3";
            this.panel3.Size = new System.Drawing.Size(557, 370);
            this.panel3.TabIndex = 3;
            // 
            // panel5
            // 
            this.panel5.Controls.Add(this.chklstUGPermit);
            this.panel5.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel5.Location = new System.Drawing.Point(0, 0);
            this.panel5.Name = "panel5";
            this.panel5.Size = new System.Drawing.Size(557, 322);
            this.panel5.TabIndex = 5;
            // 
            // chklstUGPermit
            // 
            this.chklstUGPermit.CheckOnClick = true;
            this.chklstUGPermit.ColumnWidth = 250;
            this.chklstUGPermit.Dock = System.Windows.Forms.DockStyle.Fill;
            this.chklstUGPermit.HorizontalScrollbar = true;
            this.chklstUGPermit.Location = new System.Drawing.Point(0, 0);
            this.chklstUGPermit.MultiColumn = true;
            this.chklstUGPermit.Name = "chklstUGPermit";
            this.chklstUGPermit.ScrollAlwaysVisible = true;
            this.chklstUGPermit.Size = new System.Drawing.Size(557, 308);
            this.chklstUGPermit.TabIndex = 0;
            // 
            // panel4
            // 
            this.panel4.Controls.Add(this.chkCheckAll);
            this.panel4.Controls.Add(this.cmdUpdateUGPermit);
            this.panel4.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.panel4.Location = new System.Drawing.Point(0, 322);
            this.panel4.Name = "panel4";
            this.panel4.Size = new System.Drawing.Size(557, 48);
            this.panel4.TabIndex = 4;
            // 
            // chkCheckAll
            // 
            this.chkCheckAll.Cursor = System.Windows.Forms.Cursors.Hand;
            this.chkCheckAll.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.chkCheckAll.ForeColor = System.Drawing.Color.Crimson;
            this.chkCheckAll.Location = new System.Drawing.Point(6, 6);
            this.chkCheckAll.Name = "chkCheckAll";
            this.chkCheckAll.Size = new System.Drawing.Size(148, 36);
            this.chkCheckAll.TabIndex = 4;
            this.chkCheckAll.Text = "Chọn/Bỏ chọn tất cả";
            this.chkCheckAll.CheckedChanged += new System.EventHandler(this.chkCheckAll_CheckedChanged);
            // 
            // cmdUpdateUGPermit
            // 
            this.cmdUpdateUGPermit.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.cmdUpdateUGPermit.Cursor = System.Windows.Forms.Cursors.Hand;
            this.cmdUpdateUGPermit.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.cmdUpdateUGPermit.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cmdUpdateUGPermit.ForeColor = System.Drawing.Color.Crimson;
            this.cmdUpdateUGPermit.Image = ((System.Drawing.Image)(resources.GetObject("cmdUpdateUGPermit.Image")));
            this.cmdUpdateUGPermit.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.cmdUpdateUGPermit.Location = new System.Drawing.Point(378, 6);
            this.cmdUpdateUGPermit.Name = "cmdUpdateUGPermit";
            this.cmdUpdateUGPermit.Size = new System.Drawing.Size(174, 36);
            this.cmdUpdateUGPermit.TabIndex = 3;
            this.cmdUpdateUGPermit.Text = "Cập nhật các thay đổi";
            this.cmdUpdateUGPermit.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.cmdUpdateUGPermit.Click += new System.EventHandler(this.cmdUpdateUGPermit_Click);
            // 
            // splitter2
            // 
            this.splitter2.Location = new System.Drawing.Point(168, 0);
            this.splitter2.Name = "splitter2";
            this.splitter2.Size = new System.Drawing.Size(3, 370);
            this.splitter2.TabIndex = 1;
            this.splitter2.TabStop = false;
            // 
            // pnlDataList_Man_UG
            // 
            this.pnlDataList_Man_UG.Controls.Add(this.tvUsernGroup);
            this.pnlDataList_Man_UG.Dock = System.Windows.Forms.DockStyle.Left;
            this.pnlDataList_Man_UG.Location = new System.Drawing.Point(0, 0);
            this.pnlDataList_Man_UG.Name = "pnlDataList_Man_UG";
            this.pnlDataList_Man_UG.Size = new System.Drawing.Size(168, 370);
            this.pnlDataList_Man_UG.TabIndex = 0;
            // 
            // tvUsernGroup
            // 
            this.tvUsernGroup.Cursor = System.Windows.Forms.Cursors.Default;
            this.tvUsernGroup.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tvUsernGroup.HideSelection = false;
            this.tvUsernGroup.ImageIndex = 0;
            this.tvUsernGroup.ImageList = this.imageList2;
            this.tvUsernGroup.Location = new System.Drawing.Point(0, 0);
            this.tvUsernGroup.Name = "tvUsernGroup";
            this.tvUsernGroup.SelectedImageIndex = 0;
            this.tvUsernGroup.Size = new System.Drawing.Size(168, 370);
            this.tvUsernGroup.Sorted = true;
            this.tvUsernGroup.TabIndex = 0;
            this.tvUsernGroup.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvUsernGroup_AfterSelect);
            // 
            // tpDataListMan
            // 
            this.tpDataListMan.BackColor = System.Drawing.Color.WhiteSmoke;
            this.tpDataListMan.Controls.Add(this.panel2);
            this.tpDataListMan.ImageIndex = 2;
            this.tpDataListMan.Location = new System.Drawing.Point(4, 34);
            this.tpDataListMan.Name = "tpDataListMan";
            this.tpDataListMan.Size = new System.Drawing.Size(728, 370);
            this.tpDataListMan.TabIndex = 1;
            this.tpDataListMan.Text = "DBA\'s Administrations";
            // 
            // panel2
            // 
            this.panel2.Controls.Add(this.splitter3);
            this.panel2.Controls.Add(this.pnlGridDanhMuc);
            this.panel2.Controls.Add(this.pnlTestQuery);
            this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel2.Location = new System.Drawing.Point(0, 0);
            this.panel2.Name = "panel2";
            this.panel2.Size = new System.Drawing.Size(728, 370);
            this.panel2.TabIndex = 0;
            // 
            // splitter3
            // 
            this.splitter3.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.splitter3.Location = new System.Drawing.Point(0, 207);
            this.splitter3.Name = "splitter3";
            this.splitter3.Size = new System.Drawing.Size(728, 3);
            this.splitter3.TabIndex = 1;
            this.splitter3.TabStop = false;
            // 
            // pnlGridDanhMuc
            // 
            this.pnlGridDanhMuc.Controls.Add(this.pnlDataListMan_Dgrid);
            this.pnlGridDanhMuc.Controls.Add(this.pnlDataList_Man_CMD);
            this.pnlGridDanhMuc.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pnlGridDanhMuc.Location = new System.Drawing.Point(0, 0);
            this.pnlGridDanhMuc.Name = "pnlGridDanhMuc";
            this.pnlGridDanhMuc.Size = new System.Drawing.Size(728, 210);
            this.pnlGridDanhMuc.TabIndex = 0;
            // 
            // pnlDataListMan_Dgrid
            // 
            this.pnlDataListMan_Dgrid.Controls.Add(this.dgridDataListCreate);
            this.pnlDataListMan_Dgrid.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pnlDataListMan_Dgrid.Location = new System.Drawing.Point(0, 0);
            this.pnlDataListMan_Dgrid.Name = "pnlDataListMan_Dgrid";
            this.pnlDataListMan_Dgrid.Size = new System.Drawing.Size(728, 178);
            this.pnlDataListMan_Dgrid.TabIndex = 2;
            // 
            // dgridDataListCreate
            // 
            this.dgridDataListCreate.CaptionFont = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dgridDataListCreate.CaptionText = "Bạn có thể nhập danh sách các Danh mục của hệ thống tại đây (Phần dành cho lập tr" +
                "ình viên - DBA)";
            this.dgridDataListCreate.DataMember = "";
            this.dgridDataListCreate.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dgridDataListCreate.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dgridDataListCreate.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dgridDataListCreate.Location = new System.Drawing.Point(0, 0);
            this.dgridDataListCreate.Name = "dgridDataListCreate";
            this.dgridDataListCreate.ParentRowsBackColor = System.Drawing.Color.White;
            this.dgridDataListCreate.ParentRowsForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
            this.dgridDataListCreate.Size = new System.Drawing.Size(728, 178);
            this.dgridDataListCreate.TabIndex = 1;
            this.dgridDataListCreate.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dgridDataListCreate_Navigate);
            // 
            // pnlDataList_Man_CMD
            // 
            this.pnlDataList_Man_CMD.Controls.Add(this.cmdUpdate);
            this.pnlDataList_Man_CMD.Controls.Add(this.cmdPhanQuyen);
            this.pnlDataList_Man_CMD.Controls.Add(this.cmdTestQuery);
            this.pnlDataList_Man_CMD.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.pnlDataList_Man_CMD.Location = new System.Drawing.Point(0, 178);
            this.pnlDataList_Man_CMD.Name = "pnlDataList_Man_CMD";
            this.pnlDataList_Man_CMD.Size = new System.Drawing.Size(728, 32);
            this.pnlDataList_Man_CMD.TabIndex = 0;
            // 
            // cmdUpdate
            // 
            this.cmdUpdate.Cursor = System.Windows.Forms.Cursors.Hand;
            this.cmdUpdate.Dock = System.Windows.Forms.DockStyle.Fill;
            this.cmdUpdate.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.cmdUpdate.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cmdUpdate.ForeColor = System.Drawing.Color.Orchid;
            this.cmdUpdate.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.cmdUpdate.Location = new System.Drawing.Point(176, 0);
            this.cmdUpdate.Name = "cmdUpdate";
            this.cmdUpdate.Size = new System.Drawing.Size(320, 32);
            this.cmdUpdate.TabIndex = 1;
            this.cmdUpdate.Text = "Cập nhật các thay đổi";
            this.cmdUpdate.Click += new System.EventHandler(this.cmdUpdate_Click);
            // 
            // cmdPhanQuyen
            // 
            this.cmdPhanQuyen.Cursor = System.Windows.Forms.Cursors.Hand;
            this.cmdPhanQuyen.Dock = System.Windows.Forms.DockStyle.Right;
            this.cmdPhanQuyen.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.cmdPhanQuyen.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cmdPhanQuyen.ForeColor = System.Drawing.Color.Crimson;
            this.cmdPhanQuyen.Image = ((System.Drawing.Image)(resources.GetObject("cmdPhanQuyen.Image")));
            this.cmdPhanQuyen.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.cmdPhanQuyen.Location = new System.Drawing.Point(496, 0);
            this.cmdPhanQuyen.Name = "cmdPhanQuyen";
            this.cmdPhanQuyen.Size = new System.Drawing.Size(232, 32);
            this.cmdPhanQuyen.TabIndex = 2;
            this.cmdPhanQuyen.Text = "Phân quyền sử dụng danh mục";
            this.cmdPhanQuyen.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.cmdPhanQuyen.Click += new System.EventHandler(this.cmdPhanQuyen_Click);
            // 
            // cmdTestQuery
            // 
            this.cmdTestQuery.Cursor = System.Windows.Forms.Cursors.Hand;
            this.cmdTestQuery.Dock = System.Windows.Forms.DockStyle.Left;
            this.cmdTestQuery.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.cmdTestQuery.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.cmdTestQuery.ForeColor = System.Drawing.Color.Crimson;
            this.cmdTestQuery.Image = ((System.Drawing.Image)(resources.GetObject("cmdTestQuery.Image")));
            this.cmdTestQuery.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.cmdTestQuery.Location = new System.Drawing.Point(0, 0);
            this.cmdTestQuery.Name = "cmdTestQuery";
            this.cmdTestQuery.Size = new System.Drawing.Size(176, 32);
            this.cmdTestQuery.TabIndex = 0;
            this.cmdTestQuery.Text = "Test the Select query";
            this.cmdTestQuery.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.cmdTestQuery.Click += new System.EventHandler(this.cmdTestQuery_Click);
            // 
            // pnlTestQuery
            // 
            this.pnlTestQuery.Controls.Add(this.dgridTestQuey);
            this.pnlTestQuery.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.pnlTestQuery.Location = new System.Drawing.Point(0, 210);
            this.pnlTestQuery.Name = "pnlTestQuery";
            this.pnlTestQuery.Size = new System.Drawing.Size(728, 160);
            this.pnlTestQuery.TabIndex = 0;
            // 
            // dgridTestQuey
            // 
            this.dgridTestQuey.CaptionVisible = false;
            this.dgridTestQuey.DataMember = "";
            this.dgridTestQuey.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dgridTestQuey.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dgridTestQuey.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dgridTestQuey.Location = new System.Drawing.Point(0, 0);
            this.dgridTestQuey.Name = "dgridTestQuey";
            this.dgridTestQuey.Size = new System.Drawing.Size(728, 160);
            this.dgridTestQuey.TabIndex = 0;
            // 
            // tpHelp
            // 
            this.tpHelp.BackColor = System.Drawing.Color.WhiteSmoke;
            this.tpHelp.Controls.Add(this.rtbHelp);
            this.tpHelp.ImageIndex = 3;
            this.tpHelp.Location = new System.Drawing.Point(4, 34);
            this.tpHelp.Name = "tpHelp";
            this.tpHelp.Size = new System.Drawing.Size(728, 370);
            this.tpHelp.TabIndex = 2;
            this.tpHelp.Text = "Trợ giúp";
            // 
            // rtbHelp
            // 
            this.rtbHelp.BackColor = System.Drawing.Color.WhiteSmoke;
            this.rtbHelp.Dock = System.Windows.Forms.DockStyle.Fill;
            this.rtbHelp.Location = new System.Drawing.Point(0, 0);
            this.rtbHelp.Name = "rtbHelp";
            this.rtbHelp.ReadOnly = true;
            this.rtbHelp.Size = new System.Drawing.Size(728, 370);
            this.rtbHelp.TabIndex = 0;
            this.rtbHelp.Text = "";
            // 
            // tpErrorLog
            // 
            this.tpErrorLog.BackColor = System.Drawing.Color.WhiteSmoke;
            this.tpErrorLog.Controls.Add(this.txtErrorLog);
            this.tpErrorLog.ImageIndex = 6;
            this.tpErrorLog.Location = new System.Drawing.Point(4, 34);
            this.tpErrorLog.Name = "tpErrorLog";
            this.tpErrorLog.Size = new System.Drawing.Size(728, 370);
            this.tpErrorLog.TabIndex = 4;
            this.tpErrorLog.Text = "Error log";
            // 
            // txtErrorLog
            // 
            this.txtErrorLog.BackColor = System.Drawing.Color.WhiteSmoke;
            this.txtErrorLog.Dock = System.Windows.Forms.DockStyle.Fill;
            this.txtErrorLog.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.txtErrorLog.ForeColor = System.Drawing.Color.Red;
            this.txtErrorLog.Location = new System.Drawing.Point(0, 0);
            this.txtErrorLog.Multiline = true;
            this.txtErrorLog.Name = "txtErrorLog";
            this.txtErrorLog.ReadOnly = true;
            this.txtErrorLog.Size = new System.Drawing.Size(728, 370);
            this.txtErrorLog.TabIndex = 0;
            this.toolTip1.SetToolTip(this.txtErrorLog, "Để được trợ giúp bạn vui lòng gởi các thông báo lỗi tới CNC-Soft.");
            // 
            // imageList1
            // 
            this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
            this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
            this.imageList1.Images.SetKeyName(0, "");
            this.imageList1.Images.SetKeyName(1, "");
            this.imageList1.Images.SetKeyName(2, "");
            this.imageList1.Images.SetKeyName(3, "");
            this.imageList1.Images.SetKeyName(4, "");
            this.imageList1.Images.SetKeyName(5, "");
            this.imageList1.Images.SetKeyName(6, "");
            // 
            // ep
            // 
            this.ep.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.AlwaysBlink;
            this.ep.ContainerControl = this;
            this.ep.Icon = ((System.Drawing.Icon)(resources.GetObject("ep.Icon")));
            // 
            // lblError
            // 
            this.lblError.BackColor = System.Drawing.SystemColors.Control;
            this.ep.SetIconAlignment(this.lblError, System.Windows.Forms.ErrorIconAlignment.BottomLeft);
            this.lblError.Location = new System.Drawing.Point(592, 8);
            this.lblError.Name = "lblError";
            this.lblError.Size = new System.Drawing.Size(8, 16);
            this.lblError.TabIndex = 3;
            this.lblError.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // DataListManager
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.BackColor = System.Drawing.Color.WhiteSmoke;
            this.ClientSize = new System.Drawing.Size(736, 430);
            this.Controls.Add(this.lblError);
            this.Controls.Add(this.tabControl1);
            this.Controls.Add(this.stbMain);
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "DataListManager";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "CNC-User Data Editing Permission Management";
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.Load += new System.EventHandler(this.DataListManager_Load);
            ((System.ComponentModel.ISupportInitialize)(this.sbpMessage)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbpUser)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbpServer)).EndInit();
            this.pnlMain.ResumeLayout(false);
            this.pnlDataList_Right.ResumeLayout(false);
            this.pnlDataList_Grid.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.dgridDataListEdit)).EndInit();
            this.pnlDataList_CMD.ResumeLayout(false);
            this.pnlDataList.ResumeLayout(false);
            this.tabControl1.ResumeLayout(false);
            this.tpDataList.ResumeLayout(false);
            this.tpUserPermit.ResumeLayout(false);
            this.panel1.ResumeLayout(false);
            this.panel3.ResumeLayout(false);
            this.panel5.ResumeLayout(false);
            this.panel4.ResumeLayout(false);
            this.pnlDataList_Man_UG.ResumeLayout(false);
            this.tpDataListMan.ResumeLayout(false);
            this.panel2.ResumeLayout(false);
            this.pnlGridDanhMuc.ResumeLayout(false);
            this.pnlDataListMan_Dgrid.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.dgridDataListCreate)).EndInit();
            this.pnlDataList_Man_CMD.ResumeLayout(false);
            this.pnlTestQuery.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.dgridTestQuey)).EndInit();
            this.tpHelp.ResumeLayout(false);
            this.tpErrorLog.ResumeLayout(false);
            this.tpErrorLog.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.ep)).EndInit();
            this.ResumeLayout(false);

		}
		#endregion

		#region [ Attributes ]
		private string _startupDataListName = null;

		public string StartupDataListName {
			get { return _startupDataListName; }
			set { _startupDataListName = value; }
		}
		#endregion

		#region [ Vars ]

		private CNCSoft.EData.SqlServer.SqlConnectionInfo _cnnInfo;
		private UserInfo _loginUser;

		private bool isReload = false;

		private DataSet ds;

		TreeNode _root;
		Icon errorIcon;

		private bool isSuperVisor = false;

		private enum TL {
			DataList,
			DataList_Man,
			DataList_Man_Lookup,
			UserGroup,
			UserGroupDataListPermit,
			TestQuery
		}
		#endregion

		private void DataListManager_Load(object sender, System.EventArgs e) {
			if (!isReload) {

				CNCSoft.EWinform.Waiting.ShowMessage("Loading...");

				stbMain.Panels[1].Text = _loginUser.UserID;
				stbMain.Panels[2].Text = _cnnInfo.DataSource.ToUpper();

                ds = new DataSet();
				ds.Tables.Add("DataList");					// Table to hold data list for edit		

    			ds.Tables.Add("DataList_Man");				// Khoi tao danh sach cac danh muc	|
				ds.Tables.Add("DataList_Man_Lookup");		// initDataList_Man

				if (isSuperVisor) {
					ds.Tables.Add("UserGroup");					//
					ds.Tables.Add("UserGroupDataListPermit");	// Tab phan quyen
					ds.Tables.Add("TestQuery");					// Tab quan tri
				}

				try {
					//1. Tab danh muc): khoi tao cac danh muc cua login user
					_root = new TreeNode("Danh sách các danh mục");
					tvDataList.Nodes.Add(_root);
					loadUserDataList(_root);

					if (isSuperVisor) {
						//2. Khoi tao phan quyen
						initUserGroupDataList();

						//3. Quan ly danh muc (danh co programer (// Tab quan tri)
						initDBAAdministration(true);

					} else { // Disable some functions that don't have privileges to use
						tvUsernGroup.Enabled = false;
						tvUsernGroup.BackColor = Color.WhiteSmoke;
						chklstUGPermit.Enabled = false;
						chklstUGPermit.BackColor = Color.WhiteSmoke;
						cmdTestQuery.Enabled = false;
						dgridDataListCreate.Enabled = false;
						dgridTestQuey.Enabled = false;
						cmdUpdate.Enabled = false;
						cmdUpdateUGPermit.Enabled = false;
					}

					//4. Tag Help
					//@todo

					// In case open User's datalist with a default table
					if (_startupDataListName != null) {
						foreach (TreeNode tn in _root.Nodes) {
							if (_startupDataListName.ToLower() == tn.Text.ToLower()) {
								tvDataList.SelectedNode = tn;
								break;
							}
						}
					}

					isReload = true;

				} catch (Exception ex) {
					sendStatusMessage("Lỗi khi khởi tạo chương trình....xem [Error log]");
					logError(ex);
				}

				CNCSoft.EWinform.Waiting.HideMessage();
			}
		}

        private void DataListManager_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            //MessageBox.Show(((DataListInfo)tnCurrentDL.Tag).CommandText );

            if (e.Column.ColumnName.ToUpper().Substring(0, 2) == "MA")
            {
                string Ma = e.Column.ColumnName.ToUpper();
                string DanhMuc = e.Column.ColumnName.ToUpper().Replace("MA", "DM_");

                //Neu la chinh danh muc nay thi return
                if (((DataListInfo)tnCurrentDL.Tag).CommandText.ToUpper().IndexOf(DanhMuc)>=0 ) return;

                //Khong co trong danh muc la hien list data
                try  //Neu ko co se xuong catch
                {
                    string str = CNCSoft.EData.SQLHelper.ExecuteScalar(_cnnInfo.ConnectionString,
                                "SELECT " + Ma + " FROM " + DanhMuc + " WHERE " + Ma + " = '" + e.Row[e.Column.ColumnName] + "'").ToString();
                }
                catch (Exception ex)
                {
                    //Can xu ly them truong hop khong co DanhMuc (do ngo nhan ten MA...)
                    if (ex.Message.IndexOf("'" + DanhMuc + "'") < 0)  //Bao loi lien quan den Danh Muc (Invalid Object name <DM>). Khong co DanhMuc thi thoi, ko load data list lam gi
                    {
                        e.Row[e.Column.ColumnName] = LoadListData("SELECT * FROM " + DanhMuc);
                        return;
                    }
                }
            }
        }


        //Load Danh muc tuong ung
        private string LoadListData(string strSELECT)
        {
            try
            {
                FormView fv = null;
                fv = new FormView(strSELECT, _cnnInfo.ConnectionString, DateTime.Now);
                //fv.DateFilterColumns = new string[,] { { "NgayDeNghi", "Ngày yêu cầu" } };
                //fv.CollumnFocusInFilterGrid = 3;

                fv.ShowDialog(this);
                if (fv.DialogResult == DialogResult.OK)
                {
                    return fv.SelectedIDs.Replace("'", "").Replace("(", "").Replace(")", "");
                }
                else
                    return "";
            }
            catch
            {
                return "";
            }
        }


		private void initUserGroupDataList() {
			SQLHelper.Fill(
				getTable(TL.UserGroup), 
				_cnnInfo.ConnectionString, "Select GroupId, UserId from Sys_User_Group Order by GroupId");

			// Add user and groups to tree
			DataTable tbl = getTable(TL.UserGroup);
			ArrayList al = new ArrayList();
			TreeNode group = null;
			TreeNode user;
			for (int index = 0; index < tbl.Rows.Count; index++) {
				if (al.Contains(tbl.Rows[index]["GroupId"])) { // adding to current group
					user = new TreeNode((string)tbl.Rows[index]["UserId"]);
					user.Tag = "user";
					user.ImageIndex = 4;
					user.SelectedImageIndex = 5;
					group.Nodes.Add(user);

				} else { // see new group
					al.Add(tbl.Rows[index]["GroupId"]);
					group = new TreeNode((string)tbl.Rows[index]["GroupId"]);
					group.Tag = "group";
					group.ImageIndex = 3;
					group.SelectedImageIndex = 3;
					tvUsernGroup.Nodes.Add(group);

					user = new TreeNode((string)tbl.Rows[index]["UserId"]);
					user.Tag = "user";
					user.ImageIndex = 4;
					user.SelectedImageIndex = 5;
					group.Nodes.Add(user);
				}
			}
			al.Clear();
			al = null;

			tvUsernGroup.ExpandAll();
		}

		private TreeNode tnCurrentUG;
		private void tvUsernGroup_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) {
			tnCurrentUG = e.Node;
			if (e.Node == null) {
				cmdUpdateUGPermit.Enabled = false;
				return;
			}

			cmdUpdateUGPermit.Enabled = true;


			CNCSoft.EWinform.Waiting.ShowMessage("Loading...");

			tvUsernGroup.Enabled = false;

			DataTable tblUGPermit = getTable(TL.UserGroupDataListPermit);
			
			string sqlSelect = "";
			switch ((string)e.Node.Tag) {

				case "user":
					sqlSelect = "SELECT DLU.DLId, DL.DLName, DLU.UserId, DLU.PermitUserId FROM Sys_DataList DL INNER JOIN Sys_DataList_User DLU ON DL.DLID = DLU.DLId where DLU.UserId ='" +e.Node.Text +"'";
					break;

				case "group":
					sqlSelect = "SELECT DLG.DLId, DL.DLName, DLG.GroupId, DLG.PermitUserId FROM Sys_DataList_Group DLG INNER JOIN Sys_DataList DL ON DLG.DLId = DL.DLID where DLG.GroupId ='" +e.Node.Text +"'";
					break;
			}

			chklstUGPermit.Items.Clear();
			tblUGPermit.Clear();

			SQLHelper.Fill(tblUGPermit, _cnnInfo.ConnectionString, sqlSelect);

			SqlDataReader sqldr = SQLHelper.ExecuteReader(_cnnInfo.ConnectionString, "Select DLId, DLName from Sys_DataList");

			while (sqldr.Read()) {
				DataRow[] dr = tblUGPermit.Select("DLId=" +sqldr.GetInt32(0));
				CheckState ct = dr.Length > 0 ? CheckState.Checked: CheckState.Unchecked;
				chklstUGPermit.Items.Add(new DLItem(sqldr.GetInt32(0), sqldr.GetString(1)), ct);
			}

			CNCSoft.EWinform.Waiting.HideMessage();
			tvUsernGroup.Enabled = true;
		}

		public class DLItem {
			private int _id;
			private string _name;

			public int Id {
				get { return _id; }
			}

			public string Name {
				get { return _name; }
			}

			public DLItem(int id, string name) {
				_id = id;
				_name = name;
			}

			public override string ToString() {
				return _name;
			}
		}

		private DataTable getTable(TL index) {
			return ds.Tables[(int)index];
		}

		private void initDBAAdministration(bool isFirstTimeLoading) {

			if (!isFirstTimeLoading) {
				getTable(TL.DataList_Man_Lookup).Clear();
				getTable(TL.DataList_Man).Clear();
			}

			SQLHelper.Fill(
					getTable(TL.DataList_Man), 
				_cnnInfo.ConnectionString, "Select * from Sys_DataList");

			SQLHelper.Fill(
				getTable(TL.DataList_Man_Lookup), 
				_cnnInfo.ConnectionString, "Select * from Sys_DataList_Lookup");

			if (isFirstTimeLoading) {// Create relatios && build tablestyles

				getTable(TL.DataList_Man).Columns["DLId"].AutoIncrement = true;
				getTable(TL.DataList_Man).Columns["DLName"].AllowDBNull = false;
				getTable(TL.DataList_Man).Columns["CommandType"].AllowDBNull = false;
				getTable(TL.DataList_Man).Columns["CommandText"].AllowDBNull = false;
				getTable(TL.DataList_Man).Columns["HaveLookups"].DefaultValue = 0;
				getTable(TL.DataList_Man).Columns["HideIdentityField"].DefaultValue = 1;
				getTable(TL.DataList_Man).Columns["CommandType"].DefaultValue = 1;
				getTable(TL.DataList_Man).Columns["Descriptions"].DefaultValue = "";
				getTable(TL.DataList_Man_Lookup).Columns["CommandType"].DefaultValue = 1;

				getTable(TL.DataList_Man).PrimaryKey = new DataColumn[] {getTable(TL.DataList_Man).Columns["DLid"]};

				ds.Relations.Add(
					new DataRelation("Lookup field(s)",
					new DataColumn[] {getTable(TL.DataList_Man).Columns["DLId"]},
					new DataColumn[] {getTable(TL.DataList_Man_Lookup).Columns["DLId"]}));

				dgridDataListCreate.DataSource = getTable(TL.DataList_Man);

				// Build table styles
				//-=-=-=-==-=-=-=-=-=-

				DataGridTableStyle ts = new DataGridTableStyle();
				ts.MappingName = getTable(TL.DataList_Man).TableName;

				AGridTextBoxColumn agridTC;

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "DLId";
				agridTC.HeaderText = "";
				agridTC.Width = 0;
				ts.GridColumnStyles.Add(agridTC);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "DLName";
				agridTC.HeaderText = "Tên danh mục";
				agridTC.Width = 150;
				agridTC.NullText = "";
				ts.GridColumnStyles.Add(agridTC);

				// build commandtype table
				DataTable dtCT = new DataTable("CommandType");
				DataColumn dcCTId = new DataColumn("CTId");
				dcCTId.DataType = System.Type.GetType("System.Int16");
				DataColumn dcCTName = new DataColumn("CTName");
				dcCTName.DataType = System.Type.GetType("System.String");
				dtCT.Columns.Add(dcCTId);
				dtCT.Columns.Add(dcCTName);
				DataRow dr = dtCT.NewRow();
				dr[0] = 4; dr[1] = "CommandType.StoreProcedure";
				dtCT.Rows.Add(dr);
				dr = dtCT.NewRow();
				dr[0] = 1; dr[1] = "CommandType.Text";
				dtCT.Rows.Add(dr);

				AGridMCComBoBoxColumn mcCbo = new AGridMCComBoBoxColumn(dtCT);
				mcCbo.MappingName = "CommandType";
				mcCbo.HeaderText = "CommandType";
				mcCbo.DisplayMember = "CTId";
				mcCbo.ValueMember = "CTId";
				mcCbo.Width = 100;
				ts.GridColumnStyles.Add(mcCbo);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "CommandText";
				agridTC.HeaderText = "CommandText";
				agridTC.Width = 500;
				agridTC.NullText = "";
				ts.GridColumnStyles.Add(agridTC);

				AGridClickableBoolColumn boolCol = new AGridClickableBoolColumn();
				boolCol.MappingName = "HaveLookups";
				boolCol.HeaderText = "Lookup";
				boolCol.AllowNull = false;
				boolCol.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
				boolCol.Width = 50;
				ts.GridColumnStyles.Add(boolCol);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "IdentityFieldName";
				agridTC.HeaderText = "IdentityField";
				agridTC.Width = 150;
				agridTC.NullText = "";
				ts.GridColumnStyles.Add(agridTC);

				boolCol = new AGridClickableBoolColumn();
				boolCol.MappingName = "HideIdentityField";
				boolCol.HeaderText = "HideIdentityField";
				boolCol.AllowNull = false;
				boolCol.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
				boolCol.Width = 50;
				ts.GridColumnStyles.Add(boolCol);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "Descriptions";
				agridTC.HeaderText = "Descriptions";
				agridTC.Width = 300;
				agridTC.NullText = "";
				ts.GridColumnStyles.Add(agridTC);

				//
				// Table lookup
				//
				DataGridTableStyle tsLookup = new DataGridTableStyle();
				tsLookup.MappingName = getTable(TL.DataList_Man_Lookup).TableName;

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "DLId";
				agridTC.HeaderText = "";
				agridTC.Width = 0;
				tsLookup.GridColumnStyles.Add(agridTC);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "FieldName";
				agridTC.HeaderText = "FieldName";
				agridTC.Width = 150;
				agridTC.NullText = "";
				tsLookup.GridColumnStyles.Add(agridTC);

//				// build commandtype table for command type column of lookup table
//				DataTable dtLookupCmdType = new DataTable("Lookup_CommandType");
//				DataColumn dcLoockup_CTId = new DataColumn("CTId");
//				dcLoockup_CTId.DataType = System.Type.GetType("System.Int16");
//				dtLookupCmdType.Columns.Add(dcLoockup_CTId);
//				DataColumn dcLoolup_CTName = new DataColumn("CTName");
//				dcLoolup_CTName.DataType = System.Type.GetType("System.String");
//				dtLookupCmdType.Columns.Add(dcLoolup_CTName);
//				// Add commandtypes to table
//				dr = dtLookupCmdType.NewRow();
//				dr[0] = 4; dr[1] = "CommandType.StoreProcedure";
//				dtLookupCmdType.Rows.Add(dr);
//				dr = dtLookupCmdType.NewRow();
//				dr[0] = 1; dr[1] = "CommandType.Text";
//				dtLookupCmdType.Rows.Add(dr);
//
//				AGridMCComBoBoxColumn mcCboLookup = new AGridMCComBoBoxColumn(dtLookupCmdType);
//				mcCboLookup.MappingName = "CommandType";
//				mcCboLookup.HeaderText = "CommandType";
//				mcCboLookup.DisplayMember = "CTId";
//				mcCboLookup.ValueMember = "CTId";
//				mcCboLookup.Width = 100;
//				tsLookup.GridColumnStyles.Add(mcCboLookup);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "CommandType";
				agridTC.HeaderText = "CommandType";
				agridTC.Width = 100;
				agridTC.NullText = "";
				tsLookup.GridColumnStyles.Add(agridTC);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "CommandText";
				agridTC.HeaderText = "CommandText";
				agridTC.Width = 500;
				agridTC.NullText = "";
				tsLookup.GridColumnStyles.Add(agridTC);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "DisplayMember";
				agridTC.HeaderText = "DisplayMember";
				agridTC.Width = 100;
				agridTC.NullText = "";
				tsLookup.GridColumnStyles.Add(agridTC);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "ValueMember";
				agridTC.HeaderText = "ValueMember";
				agridTC.Width = 100;
				agridTC.NullText = "";
				tsLookup.GridColumnStyles.Add(agridTC);

				agridTC = new AGridTextBoxColumn();
				agridTC.MappingName = "Descriptions";
				agridTC.HeaderText = "Descriptions";
				agridTC.Width = 500;
				agridTC.NullText = "";
				tsLookup.GridColumnStyles.Add(agridTC);

				dgridDataListCreate.TableStyles.Add(ts);
				dgridDataListCreate.TableStyles.Add(tsLookup);

				DataGridStyleFactory gridSF = new DataGridStyleFactory();
				gridSF.applyStyleUseRandom(dgridDataListCreate);
				ts.PreferredRowHeight = 60;
				tsLookup.PreferredRowHeight = 45;
			}			
		}

		private void cmdUpdate_Click(object sender, System.EventArgs e) {

			DataTable man = getTable(TL.DataList_Man);
			DataTable lookup = getTable(TL.DataList_Man_Lookup);

			if ((man.GetChanges() == null && lookup.GetChanges() == null)) {
				sendStatusMessage("Dữ liệu chưa thay đổi nên không thể cập nhật !.");
				return;
			}

			DialogResult dr = MessageBox.Show(this, "Bạn có thật sự muốn cập nhật các thay đổi hay không ?.", 
				"Comfirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

			if (dr == DialogResult.Yes) {

				// updating

				SqlConnection sqlcn = new SqlConnection(_cnnInfo.ConnectionString);
				sqlcn.Open();

				SqlTransaction sqltran = sqlcn.BeginTransaction();

				SqlDataAdapter sqldaMaster = new SqlDataAdapter("Select * from Sys_DataList", sqlcn);
				SqlDataAdapter sqldaDetail = new SqlDataAdapter("Select * from Sys_DataList_Lookup", sqlcn);

				CNCSoft.EData.DataHelper.buildDataCommands(ref sqldaMaster, ref sqltran);
				CNCSoft.EData.DataHelper.buildDataCommands(ref sqldaDetail, ref sqltran);

				try {

					DataTable dtChanged;
					
					//Delete
					dtChanged = lookup.GetChanges(DataRowState.Deleted);
					if (dtChanged != null) sqldaDetail.Update(dtChanged);
					dtChanged = man.GetChanges(DataRowState.Deleted);
					if (dtChanged != null) sqldaMaster.Update(dtChanged);
					//Insert
					dtChanged = man.GetChanges(DataRowState.Added);
					if (dtChanged != null) sqldaMaster.Update(dtChanged);
					dtChanged = lookup.GetChanges(DataRowState.Added);
					if (dtChanged != null) sqldaDetail.Update(dtChanged);
					//Modify
					dtChanged = man.GetChanges(DataRowState.Modified);
					if (dtChanged != null) sqldaMaster.Update(dtChanged);
					dtChanged = lookup.GetChanges(DataRowState.Modified);
					if (dtChanged != null) sqldaDetail.Update(dtChanged);

					sqltran.Commit();
					getTable(TL.DataList_Man).AcceptChanges();
					getTable(TL.DataList_Man_Lookup).AcceptChanges();

					sendStatusMessage("Dữ liệu đã được cập nhật thành công (" +DateTime.Now.ToString() +")");

					// Re-init: 
					initDBAAdministration(false);

					// In delete case we will meet this, so we re-init in any cases
					loadUserDataList(_root);

					// Clear cache(s) in datalist
					hashDLTables.Clear();
					hashDLTables.Clear();

					sendStatusMessage("Bạn vui lòng chọn menu phân quyền sử dụng để phân quyền !.");
				}
				catch (Exception ex) {
					try {
						sqltran.Rollback();
					} catch {}
					MessageBox.Show(ex.ToString());
					logError(ex);
				}				
			}
		}

		private void loadUserDataList(TreeNode root) {
			root.Nodes.Clear();
			root.ImageIndex = 0;
			root.SelectedImageIndex = 0;
			
			SqlDataReader sqldr = SQLHelper.ExecuteReader(
				_cnnInfo.ConnectionString, CommandType.StoredProcedure, "sys_sp_GetDataListByUser",
				new SqlParameter[]{new SqlParameter("@userId", _loginUser.UserID)});

			while (sqldr.Read()) {
				DataListInfo dlInfo = new DataListInfo(
					sqldr.GetInt32(0),
					sqldr.GetString(1), 
					sqldr.GetInt16(2) == 1 ? CommandType.Text:CommandType.StoredProcedure,
					sqldr.GetString(3),
					sqldr.GetBoolean(4),
					sqldr.GetString(5),
					sqldr.GetString(6),
					sqldr.GetBoolean(7));

				TreeNode tr = new TreeNode(dlInfo.Name);
				tr.Tag = dlInfo;

				root.Nodes.Add(tr);

				root.ExpandAll();
			}
			sqldr.Close();
			sqldr = null;
		}		

		private void loadAllDataList() {
			
		}

		private void loadDataListManagement() {
			
		}

		private void cmdTestQuery_Click(object sender, System.EventArgs e) {
			int start = DateTime.Now.Millisecond;
			try {
				int crow = dgridDataListCreate.CurrentCell.RowNumber;
				if (crow != -1) {
					
					DataTable tbl = new DataTable();
					SQLHelper.Fill(tbl, _cnnInfo.ConnectionString, 
						(Int16)dgridDataListCreate[crow, 2] == 1 ? CommandType.Text:CommandType.StoredProcedure,
						(string)dgridDataListCreate[crow, 3],
						null);
					dgridTestQuey.DataSource = tbl;
					int end = DateTime.Now.Millisecond;

					sendStatusMessage("Executing the query took " +(end-start) +" milliseconds (about " +(double)(end-start)/1000 +" seconds) !.");
				}
			}
			catch (Exception ex) {
				sendStatusMessage(ex.Message, true);
				logError(ex);
			}
		}

		
	
		private Hashtable hashDLTables; // Hold loaded datalist for editing
		private Hashtable hashDLTSs;	// Hold tablestyles of datalist grid
		private TreeNode tnCurrentDL;
		private void tvDataList_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) {

			if (e.Node == null || e.Node == tvDataList.Nodes[0]) {
				return;
			}
			cmdCancelDL.Enabled = false;
			cmdUpdateDL.Enabled = false;
			dgridDataListEdit.Enabled = false;
			tvDataList.Enabled = false;
			ep.SetError(lblError, null);

			tnCurrentDL = e.Node;
			dgridDataListEdit.CaptionText = e.Node.Text;

			// Get the current data list information (contain in tag of node)
			DataListInfo dlInfo = (DataListInfo)e.Node.Tag;

			if (hashDLTables == null) {
				hashDLTables = new Hashtable();
				hashDLTSs = new Hashtable();
			}

			CNCSoft.EWinform.Waiting.ShowMessage("Clear data...");

			DataTable tblDL = null;
			dgridDataListEdit.TableStyles.Clear();
			dgridDataListEdit.DataSource = null;

			
			if (hashDLTables.ContainsKey(dlInfo.Id)) {// If this table was loaded the get it form cache

				CNCSoft.EWinform.Waiting.ShowMessage("Get data from Cache...");

				tblDL = (DataTable)hashDLTables[dlInfo.Id];
				dgridDataListEdit.DataSource = tblDL;
				dgridDataListEdit.TableStyles.Add((DataGridTableStyle)hashDLTSs[dlInfo.Id]);

			} else { // If was not loaded then load and insert into cache

				///
				/// Create DataTable (Datasource
				///
				CommandType cmdType = (CommandType)dlInfo.CommandType;
				tblDL = new DataTable(dlInfo.Name);

				CNCSoft.EWinform.Waiting.ShowMessage("Loading data from " +_cnnInfo.InitialCatalog +"@" +_cnnInfo.DataSource +" ...");

				try {
					SQLHelper.Fill(tblDL, _cnnInfo.ConnectionString, cmdType, dlInfo.CommandText, null);
					if (dlInfo.IdentityFieldName != string.Empty) {
						tblDL.Columns[dlInfo.IdentityFieldName].AutoIncrement = true;
					}
				}catch (Exception ex) {
					sendStatusMessage("Sai câu lệnh truy vấn, bạn hãy yêu cầu người quản trị CSDL để sửa lỗi !.", true);
					logError(ex);
					CNCSoft.EWinform.Waiting.HideMessage();
					tvDataList.Enabled =true;
					return;
				}

				CNCSoft.EWinform.Waiting.ShowMessage("Adding data into Cache....");

				hashDLTables.Add(dlInfo.Id, tblDL);

				dgridDataListEdit.DataSource = tblDL;

				// load lookup field
				CNCSoft.EWinform.Waiting.ShowMessage("Loading lookup fields....");

				Hashtable hashLookupFields = new Hashtable();
				SqlDataReader sqldr = SQLHelper.ExecuteReader(
					_cnnInfo.ConnectionString,
					"Select DLId, FieldName, CommandType, CommandText, DisplayMember, ValueMember, Descriptions from Sys_DataList_Lookup where DLid = " + dlInfo.Id);
				while (sqldr.Read()) {
					hashLookupFields.Add(sqldr.GetString(1), new LookupFieldInfo (
						sqldr.GetInt32(0), sqldr.GetString(1), (CommandType)sqldr.GetInt16(2), sqldr.GetString(3), sqldr.GetString(4), sqldr.GetString(5), sqldr.GetString(6)));
				}

				//
				// Create DataGrid tablestyle
				//
				CNCSoft.EWinform.Waiting.ShowMessage("Creating gridstyle....");

				DataGridTableStyle ts = new DataGridTableStyle();
				ts.MappingName = tblDL.TableName;

				DataColumn dc;

				for (int indexCol = 0; indexCol < tblDL.Columns.Count; indexCol++) {
                    string dtType = tblDL.Columns[indexCol].DataType.ToString();
					dc = tblDL.Columns[indexCol];
					
					if (hashLookupFields.ContainsKey(dc.ColumnName)) { // have lookup field

						LookupFieldInfo lfInfo = (LookupFieldInfo)hashLookupFields[dc.ColumnName];

						CNCSoft.EWinform.Waiting.ShowMessage("Loading lookup (" +lfInfo.FieldName +")....");

						DataTable tblLookup = new DataTable(dc.ColumnName);
						SQLHelper.Fill(tblLookup, _cnnInfo.ConnectionString, 
							lfInfo.CommandType, lfInfo.CommandText, null);

						AGridMCComBoBoxColumn mcCbo = new AGridMCComBoBoxColumn(tblLookup);
						mcCbo.MappingName = dc.ColumnName;
						mcCbo.DisplayMember = lfInfo.DisplayMember;
						mcCbo.ValueMember = lfInfo.ValueMember;
						mcCbo.HeaderText = dc.ColumnName;
						mcCbo.NullText = "";
						ts.GridColumnStyles.Add(mcCbo);

					} else { // don't have lookup field
						CNCSoft.EWinform.Waiting.ShowMessage("Creating column (" +dc.ColumnName +")....");

						if (dtType ==  "System.Int16" || dtType ==  "System.Int32" || dtType ==  "System.Int64") {

							AGridTextBoxColumn dgridFTC = new AGridTextBoxColumn();
							dgridFTC.MappingName = dc.ColumnName;
							dgridFTC.HeaderText = dc.ColumnName;
							dgridFTC.NullText = "";
							dgridFTC.Format = "N0";
							ts.GridColumnStyles.Add(dgridFTC);

						} else if (dtType ==  "System.Decimal" || dtType ==  "System.Double") {
							AGridTextBoxColumn dgridFTC = new AGridTextBoxColumn();
							dgridFTC.MappingName = dc.ColumnName;
							dgridFTC.HeaderText = dc.ColumnName;
							dgridFTC.NullText = "";
							dgridFTC.Format = "N";
							ts.GridColumnStyles.Add(dgridFTC);

						} else if (dtType ==  "System.Boolean") {
							AGridClickableBoolColumn BoolCol = new AGridClickableBoolColumn();
							BoolCol.MappingName = dc.ColumnName;
							BoolCol.HeaderText = dc.ColumnName;
							BoolCol.Alignment = HorizontalAlignment.Center;
							BoolCol.NullText = "";
							BoolCol.AllowNull = false;
							ts.GridColumnStyles.Add(BoolCol);

						} else if (dtType ==  "System.DateTime") {
							AGridDateTimeColumn dtCol = new AGridDateTimeColumn();
							dtCol.MappingName = dc.ColumnName;
							dtCol.HeaderText = dc.ColumnName;
							dtCol.Alignment = HorizontalAlignment.Center;
							dtCol.NullText = "";
							dtCol.DateTimePicker.Format = DateTimePickerFormat.Short;
							ts.GridColumnStyles.Add(dtCol);
						} else {
							AGridTextBoxColumn dgridFTC = new AGridTextBoxColumn();
							dgridFTC.MappingName = dc.ColumnName;
							dgridFTC.HeaderText = dc.ColumnName;
							dgridFTC.NullText = "";
							ts.GridColumnStyles.Add(dgridFTC);
						}

						if (dlInfo.IdentityFieldName != string.Empty && dlInfo.IdentityFieldName == ts.GridColumnStyles[indexCol].MappingName) {
							ts.GridColumnStyles[indexCol].ReadOnly = true;
							if (dlInfo.HideIdentityField) {
								ts.GridColumnStyles[indexCol].HeaderText = "";
								ts.GridColumnStyles[indexCol].Width = 0;
							}
						}
						else {
							//gridARS.AutoSizeColumn(indexCol);
						}

					}// // don't have lookup field
				} // for (int indexCol = 0; indexCol < tblDL.Columns.Count; indexCol++)

				//Free resources
				hashLookupFields.Clear();
				hashLookupFields = null;

				CNCSoft.EWinform.Waiting.ShowMessage("Applying style....");
				dgridDataListEdit.TableStyles.Add(ts);
				DataGridStyleFactory dgridSF = new DataGridStyleFactory();
				dgridSF.applyStyleUseRandom(dgridDataListEdit);

				DataGridAutoResizeSupporter gridARS = new DataGridAutoResizeSupporter(dgridDataListEdit);
				gridARS.AutoSizeGrid();

				CNCSoft.EWinform.Waiting.ShowMessage("Adding gridstyle into cache....");
				hashDLTSs.Add(dlInfo.Id, ts);

			}//else { // If was not loaded then load and insert into cache

			tvDataList.Enabled = true;
			cmdCancelDL.Enabled = true;
			cmdUpdateDL.Enabled = true;
			dgridDataListEdit.Enabled = true;

			CNCSoft.EWinform.Waiting.HideMessage();

			sendStatusMessage("Bạn vừa chọn để chỉnh sửa danh mục: " +e.Node.Text);

			this.Focus();
			this.SelectNextControl(ActiveControl, true, true, true, true);
			try {
				dgridDataListEdit.CurrentCell = new DataGridCell(
					tblDL.Rows.Count +1,
					dgridDataListEdit.CurrentCell.ColumnNumber);
				dgridDataListCreate.Select(tblDL.Rows.Count +1);
			} catch {}

            tblDL.ColumnChanged += new DataColumnChangeEventHandler(DataListManager_ColumnChanged);

		}

		private void cmdUpdateDL_Click(object sender, System.EventArgs e) {
			try {
				dgridDataListEdit.CurrentCell = new DataGridCell(
					dgridDataListEdit.CurrentCell.RowNumber +1,
					dgridDataListEdit.CurrentCell.ColumnNumber);
			} catch {}

			try {

				DataTable ds = (DataTable)dgridDataListEdit.DataSource;
				if (ds == null) {
					cmdUpdateDL.Enabled = false;
					sendStatusMessage("Bạn vui lòng chọn danh mục để chỉnh sửa.", true);
					return;
				} else if (ds.GetChanges() == null) {
					sendStatusMessage("Dữ liệu chưa thay đổi nên không thể cập nhật.");
					return;
				}

				DialogResult dr = MessageBox.Show(this, "Bạn có thật sự muốn cập nhật các thay đổi đối với danh mục này không ?",
					"Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
				if (dr == DialogResult.Yes) {
					DataListInfo dlInfo = (DataListInfo)tnCurrentDL.Tag;
					SqlDataAdapter sqlda = new SqlDataAdapter(dlInfo.CommandText, _cnnInfo.ConnectionString);
					DataHelper.buildDataCommands(ref sqlda);
					DataTable dt = (DataTable)dgridDataListEdit.DataSource;
                
                // return to client [created id]
                    if (_startupDataListName != null)
                    {

                        if (_startupDataListName.ToLower() == tnCurrentDL.Text.ToLower() && returnColumnName != null)
                        {
                            DataTable dtTemp = dt.GetChanges(DataRowState.Added);
                            if (dtTemp != null && dtTemp.Rows.Count > 0)
                            {
                                try
                                {
                                    createId = dtTemp.Rows[dtTemp.Rows.Count - 1][returnColumnName].ToString();
                                }
                                catch { }
                            }
                        }
                    }

					sqlda.Update(dt);

				

					dt.AcceptChanges();

					sendStatusMessage("Dữ liệu đã được cập nhật thành công (" +DateTime.Now.ToString() +")");
				}
			} catch (Exception ex) {
				sendStatusMessage("Lỗi khi cập nhận dữ liệu (" +DateTime.Now.ToString() +")");
				logError(ex);
			}
		}
		private string createId = null; // Used to return to client form (calling form)
		private string returnColumnName = null;

	
		private void cmdCancelDL_Click(object sender, System.EventArgs e) {
			DataTable ds = (DataTable)dgridDataListEdit.DataSource;
			if (ds != null && ds.GetChanges() != null) {
				DialogResult dr = MessageBox.Show(this, "Bạn có thật sự muốn bỏ qua các thay đổi đối với danh mục này không ?",
					"Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
				if (dr == DialogResult.Yes) {
					ds.RejectChanges();
				}
			}
		}

		private void cmdUpdateUGPermit_Click(object sender, System.EventArgs e) {

			if (tnCurrentUG == null) {
				MessageBox.Show(this, "Bạn vui lòng chọn User hoặc Group trước khi cập nhật !.", "Message",
					MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}

			cmdUpdateUGPermit.Enabled = false;
			CNCSoft.EWinform.Waiting.ShowMessage("Updating...");

			SqlConnection sqlcn = new SqlConnection(_cnnInfo.ConnectionString);
			sqlcn.Open();
			SqlTransaction sqltran = sqlcn.BeginTransaction();

			string delCmd = null;
			string insertCmd = null;
			switch ((string)tnCurrentUG.Tag) {
				case "user":
					delCmd = "Delete From Sys_DataList_User Where UserId = '" +tnCurrentUG.Text +"'";
					insertCmd = "Insert into Sys_DataList_User values(@1, @2, @3)";
					break;

				case "group":
					delCmd = delCmd = "Delete From Sys_DataList_Group Where GroupId = '" +tnCurrentUG.Text +"'";
					insertCmd = "Insert into Sys_DataList_Group values(@1, @2, @3)";
					break;
			}

			SQLHelper.ExecuteNonQuery(sqltran, delCmd);
			try {	
				DLItem ilItem;
				IEnumerator ie =  chklstUGPermit.CheckedItems.GetEnumerator();
				string realInsertCmd;
				while (ie.MoveNext()) {
					ilItem = (DLItem)ie.Current;

					CNCSoft.EWinform.Waiting.ShowMessage("Insert " +ilItem.Name);
					realInsertCmd = null;
					realInsertCmd = insertCmd.Replace("@1", "" +ilItem.Id);
					realInsertCmd = realInsertCmd.Replace("@2", "'" +tnCurrentUG.Text +"'");
					realInsertCmd = realInsertCmd.Replace("@3", "'" +_loginUser.UserID +"'");

					SQLHelper.ExecuteNonQuery(sqltran, realInsertCmd);
				}
				sqltran.Commit();

				sendStatusMessage("Dữ liệu đã được cập nhật thành công (" +DateTime.Now.ToString() +")");

				loadUserDataList(_root);
			}
			catch (Exception ex) {
				sqltran.Rollback();
				CNCSoft.EWinform.Waiting.HideMessage();
				logError(ex);
			}
			finally {
				CNCSoft.EWinform.Waiting.HideMessage();
				cmdUpdateUGPermit.Enabled = true;
				sqlcn.Close();
				sqlcn.Dispose();				
			}			
		}

		private void chkCheckAll_CheckedChanged(object sender, System.EventArgs e) {
			bool check;
			if (!chkCheckAll.Checked) {
				check = false;
			} else {
				check = true;
			}
			for (int index = 0; index < chklstUGPermit.Items.Count; index++) {
				chklstUGPermit.SetItemChecked(index, check);
			}
		}

		private void mniRefresh_Click(object sender, System.EventArgs e) {
			this.loadUserDataList(_root);
		}

		private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e) {
			if (!isSuperVisor && (tabControl1.SelectedIndex == 1 || tabControl1.SelectedIndex == 2)) {
				sendStatusMessage("Bạn không có quyền để dùng chức năng này !.");
			}
		}

		private void sendStatusMessage(string message) {
			sendStatusMessage(message, false);
			
		}

		private void logError(string message) {
			txtErrorLog.Text += "Error (" +DateTime.Now.ToString() +"): " +message +(char)13 +(char)10 +(char)13 +(char)10;
			ep.SetError(lblError, "Error Occurred !.");
			sbpMessage.Icon = errorIcon;
		}

		private void cmdPhanQuyen_Click(object sender, System.EventArgs e) {
			this.tabControl1.SelectedIndex = 1;
		}

		private void sendStatusMessage(string message, bool error) {
			if (error) {
				stbMain.Panels[0].Text = "Error: " +message;
			} else {
				sbpMessage.Icon = null;
				stbMain.Panels[0].Text = message;
			}
		}

		private void logError(Exception ex) {
			logError(ex.ToString());
		}

		/// <summary>
		/// Return has been created Id by user
		/// </summary>
		/// <returns></returns>
		public string getCreatedID() {
			return createId;
		}

        private void dgridDataListCreate_Navigate(object sender, NavigateEventArgs ne)
        {

        }
		
	}
}
